﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;

namespace MinistryStandardPlatformWeb.Controllers
{
    public class RightsController : Controller
    {

        private MSPDataContext context = new MSPDataContext();
        //
        // GET: /Rights/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AddRights(string id)
        {
            LoginUsers loginUser = new LoginUsers();
            loginUser.UserId = CommonFunctions.GetLoginUser().UserId;
            LoginUsers rightUser = new LoginUsers();
            rightUser.UserId = id;

            List<ZTreeNode> vehicleRights = this.GetVehicleRights(loginUser, rightUser);
            List<ZTreeNode> menuRights = this.GetMenuRights(loginUser, rightUser);

            ViewBag.vehicleRightsJson = CommonFunctions.ListToJsonStr<ZTreeNode>(vehicleRights);
            ViewBag.menuRightsJson = CommonFunctions.ListToJsonStr<ZTreeNode>(menuRights);
            ViewBag.userId = id;
            return View();
        }

        [HttpPost]
        public ActionResult SubmitRights(string rightsJson, string userId, int operType)
        {//operType为操作类型，1为车辆单位权限，2为菜单权限，3为指令权限
            List<ZTreeNode> list = JsonToObj(rightsJson, typeof(List<ZTreeNode>)) as List<ZTreeNode>;
            Hashtable ret = new Hashtable();
            if (operType == 1)
            {
                try
                {
                    List<RightsDetails> vehicleRights = this.context.RightsDetails.Where(t => t.UserId == userId).ToList();
                    foreach (RightsDetails rd in vehicleRights)
                    {
                        this.context.RightsDetails.DeleteOnSubmit(rd);
                    }
                    if (list != null)
                    {
                        foreach (ZTreeNode node in list)
                        {
                            RightsDetails newRight = new RightsDetails();
                            newRight.UserId = userId;
                            newRight.NodeId = node.id;
                            newRight.NodeName = node.name;
                            newRight.ParentNodeId = node.pId;
                            if (newRight.NodeId.Substring(0, 4).Equals("VEHI"))
                            {//车辆
                                newRight.NodeTYPE = false;
                            }
                            else
                            {//单位
                                newRight.NodeTYPE = true;
                            }

                            ///*查看是否有父节点*/
                            //bool hasFind = false;
                            //foreach (ZTreeNode tmp in list)
                            //{
                            //    if (newRight.ParentNodeId == tmp.id)
                            //    {
                            //        hasFind = true;
                            //        break;
                            //    }
                            //}
                            //if (!hasFind)
                            //{
                            //    newRight.ParentNodeId = null;
                            //}

                            newRight.HasRight = node.@checked;
                            newRight.InsertUserID = CommonFunctions.GetLoginUser().UserId;
                            this.context.RightsDetails.InsertOnSubmit(newRight);
                        }
                    }
                    this.context.SubmitChanges();
                    ret.Add("success", true);
                }
                catch
                {
                    ret.Add("success", false);
                }
            }
            if (operType == 2)
            {
                try
                {
                    List<MenuRights> menuRights = this.context.MenuRights.Where(t => t.UserId == userId).ToList();
                    foreach (MenuRights mr in menuRights)
                    {
                        this.context.MenuRights.DeleteOnSubmit(mr);
                    }
                    if (list != null)
                    {
                        foreach (ZTreeNode node in list)
                        {
                            MenuRights newRight = new MenuRights();
                            newRight.UserId = userId;
                            newRight.MenuId = node.id;
                            newRight.MenuName = node.name;
                            newRight.ParentMenuId = node.pId;
                            newRight.RightType = node.others;
                            newRight.Insertuserid = CommonFunctions.GetLoginUser().UserId;
                            newRight.Finserttime = DateTime.Now;
                            this.context.MenuRights.InsertOnSubmit(newRight);
                        }
                    }
                    this.context.SubmitChanges();
                    ret.Add("success", true);
                }
                catch (Exception e)
                {
                    ret.Add("success", false);
                }
            }
            return Json(ret);
        }
        //获取用户单位和车辆权限
        private List<ZTreeNode> GetVehicleRights(LoginUsers loginUser, LoginUsers rightUser)
        {//loginUser权限授予者，rightUser权限接受者
            List<RightsDetails> rights = null;
            List<RightsDetails> hasRights = null;
            List<ZTreeNode> nodes = null;
            if (!string.IsNullOrEmpty(loginUser.UserId))
            {
                rights = this.context.RightsDetails.Where(t => t.UserId == loginUser.UserId).ToList();
            }
            if (!string.IsNullOrEmpty(rightUser.UserId))
            {
                hasRights = this.context.RightsDetails.Where(t => t.UserId == rightUser.UserId).ToList();
            }
            if (rights != null)
            {
                nodes = new List<ZTreeNode>();
                foreach (RightsDetails right in rights)
                {
                    ZTreeNode node = new ZTreeNode();
                    node.id = right.NodeId;
                    node.name = right.NodeName;
                    node.pId = right.ParentNodeId;
                    if (right.NodeTYPE == true)
                    {//单位
                        node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                    }
                    else
                    {//车
                        node.icon = "/Content/themes/zTreeStyle/img/diy/car.png";
                    }
                    foreach (RightsDetails hasRight in hasRights)
                    {
                        if (hasRight.NodeId.Equals(right.NodeId)) //&& hasRight.HasRight == true)
                        {//已经拥有该权限
                            node.@checked = true;
                            break;
                        }
                    }
                    nodes.Add(node);
                }
            }
            return nodes;
        }
        //获取用户菜单权限
        private List<ZTreeNode> GetMenuRights(LoginUsers loginUser, LoginUsers rightUser)
        {//loginUser权限授予者，rightUser权限接受者
            List<MenuRights> rights = null;
            List<MenuRights> hasRights = null;
            List<ZTreeNode> nodes = null;
            if (!string.IsNullOrEmpty(loginUser.UserId))
            {
                rights = this.context.MenuRights.Where(t => t.UserId == loginUser.UserId).ToList();
            }
            if (!string.IsNullOrEmpty(rightUser.UserId))
            {
                hasRights = this.context.MenuRights.Where(t => t.UserId == rightUser.UserId).ToList();
            }
            if (rights != null)
            {
                nodes = new List<ZTreeNode>();
                foreach (MenuRights right in rights)
                {
                    ZTreeNode node = new ZTreeNode();
                    node.id = right.MenuId;
                    node.name = right.MenuName;
                    node.pId = right.ParentMenuId;
                    node.others = right.RightType;
                    foreach (MenuRights hasRight in hasRights)
                    {
                        if (hasRight.MenuId.Equals(right.MenuId))
                        {//已经拥有该权限
                            node.@checked = true;
                            break;
                        }
                    }
                    nodes.Add(node);
                }
            }
            return nodes;
        }

        //json字符串转为对象
        public static Object JsonToObj(String json, Type t)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    return serializer.ReadObject(ms);
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
